package com.zhangtai.modules.controller.admin;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangtai.Neusoft.constVo.EmployeeInfoConst;
//import com.zhangtai.Neusoft.service.NeuEmployeeBaseInfoService;
import com.zhangtai.Neusoft.service.NeuEmployeeSalaryService;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.constVo.NoticeConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.*;
//import com.zhangtai.modules.dao.ssqlDao.EmployeeBaseDao;
//import com.zhangtai.modules.dao.ssqlDao.JobDaoMssql;
//import com.zhangtai.modules.dao.ssqlDao.SsqlSalaryGoupDao;
import com.zhangtai.modules.dto.*;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.salary.*;
import com.zhangtai.modules.entity.system.AuthorityLogEntity;
import com.zhangtai.modules.entity.transfer.TransferInfoEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.common.ImgUrlService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.salary.*;
import com.zhangtai.modules.service.system.AuthorityLogService;
import com.zhangtai.modules.service.transfer.TransferInfoService;
import com.zhangtai.modules.vo.*;
import com.zhangtai.utils.*;
import com.zhangtai.utils.Excel.EntityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import com.zhangtai.utils.DateUtils;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("salary")
@Api(tags = "薪酬与带宽接口")
@Slf4j
public class SalaryController {


    @Autowired
    private SalaryBandService salaryBandService;

    @Autowired
    private EmployeeInfoService employeeInfoService;


    @Autowired
    private TransferInfoService transferInfoService;

//    @Autowired
//    SsqlSalaryGoupDao ssqlSalaryGoupDao;
    @Autowired
    private LoginController loginController;
    @Autowired
    private JobController jobController;

    @Autowired
    private AwardInfoService awardInfoService;

    @Autowired
    private AwardApplicantService awardApplicantService;
    @Autowired
    private AwardInfoDao awardInfoDao;
    @Autowired
    private AwardApplicantDao awardApplicantDao;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private UserBankCardService userBankCardService;
    @Autowired
    private UserBankCardDao userBankCardDao;

    @Autowired
    private SalaryChangeDao salaryChangeDao;
    @Autowired
    private SalaryChangeService salaryChangeService;

    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private BaseMssqlServiceImpl commonService;
    @Autowired
    private ImgUrlDao imgUrlDao;
    @Autowired
    private ImgUrlService imgUrlService;
    @Autowired
    private NoticeController noticeController;
    @Autowired
    private SalaryDistributionDao salaryDistributionDao;
    @Autowired
    private SalaryDistributionService salaryDistributionService;
    @Autowired
    private SalaryDistributionRecordingService salaryDistributionRecordingService;

    @Autowired
    private AuthorityLogService authorityLogService;
//    @Autowired
//    private JobDaoMssql jobDaoMssql;
    @Autowired
    private AwardPackageDao awardPackageDao;
    @Autowired
    private AwardPackageService awardPackageService;
    @Autowired
    private NeuEmployeeSalaryService neuEmployeeSalaryService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrgGroupDao orgGroupDao;
    @Autowired
    private ComputerSubsidyDao computerSubsidyDao;
    @Autowired
    private DimissionController dimissionController;
//
//    @Autowired
//    private EmployeeBaseDao employeeBaseDao;

    @Autowired
    private UserController userController;

    private List<Long> getSalaryOrgIds(List<Long> salaryGroupIds) {
        List<SalaryGroupDto> salaryGroupDtos = jobController.salaryGroupMap.get("salaryGroupMap");
        List<Long> orgIds = new ArrayList<>();
        Map<String, Long> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(salaryGroupIds)) {
            List<Long> Ids = JSON.parseArray(salaryGroupIds.toString(), Long.class);
            for (SalaryGroupDto item : salaryGroupDtos) {
                if (item.getOrgId().equals(new Long(1))) {
                    item.setOrgId(new Long(328323));
                }
                map.put(item.getCoidGroup().toString(), item.getOrgId());
            }

            if (!CollectionUtils.isEmpty(Ids)) {
                for (int i = 0; i < Ids.size(); i++) {
                    if (map.get(Ids.get(i).toString()) != null) {
                        orgIds.add(map.get(Ids.get(i).toString()));
                    }
                }
            }
        }
        return orgIds;

    }

//    @Autowired
//    private NeuEmployeeBaseInfoService neuEmployeeBaseInfoService;
    @Autowired
    private ComputerSubsidyService computerSubsidyService;

    @PostMapping("/addSalaryBand")
    @ApiOperation(value = "添加薪酬带宽")
    @SysAuthorityLog(value = "添加薪酬带宽")
    @PreAuthorize("hasAuthority('emp:xzkd:update')")
    public R addSalaryBand(@RequestBody @Valid SalaryBandVo salaryBandVo) {
        SalaryBandEntity salaryBandEntity = BeanUtilsMabach.doToDto(salaryBandVo, SalaryBandEntity.class);
        return salaryBandService.saveE(salaryBandEntity);

    }

    @PostMapping("/test")
    public R test(@RequestParam String id){
        SalaryDistributionEntity salaryDistributionEntity= salaryDistributionService.getByIdE(Long.valueOf(id));
        LambdaUpdateWrapper<SalaryDistributionEntity> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.set(SalaryDistributionEntity::getOidPayrollUnitId,null);
        salaryDistributionDao.update(salaryDistributionEntity,updateWrapper );
        return R.ok();
    }




    @PostMapping("/updateSalaryBand")
    @ApiOperation(value = "修改薪酬带宽")
    @SysAuthorityLog(value = "修改薪酬带宽")
    @PreAuthorize("hasAuthority('emp:xzkd:update')")
    public R updateSalaryBand(@RequestBody @Valid UpdateSalaryBandVo updateSalaryBandVo) {
        SalaryBandEntity salaryBandEntity = BeanUtilsMabach.doToDto(updateSalaryBandVo, SalaryBandEntity.class);
        salaryBandEntity.setCrateTime(new Date());


        return salaryBandService.updateByIdE(salaryBandEntity);

    }

    @DeleteMapping("/deleteSalaryBand/{id}")
    @ApiOperation(value = "根据id删除薪酬带宽")
    @SysAuthorityLog(value = "根据id删除薪酬带宽")
    @PreAuthorize("hasAuthority('emp:xzkd:update')")
    public R updateSalaryBand(@PathVariable("id") Long id) {


        return salaryBandService.removeOneById(id);

    }


    @GetMapping("/getSalaryBandList")
    @ApiOperation(value = "分页查询薪资带宽")
    @PreAuthorize("hasAuthority('emp:xzkd:get')")
    public R<PageResult<SalaryBandEntity>> getSalaryBandList(@RequestParam(value = "orgSystemId", required = false) Long systemId,
                                                             @RequestParam(value = "orgLineId", required = false) Long lineId,
                                                             @RequestParam(value = "jobLevelId", required = false) Long jobLevelId,
                                                             @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                             @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) throws Exception {

        //获取当前用户角色下公司Id 薪资权限
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }

        R uR = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) uR.getData();
        String userId = user.getString("id");
//        List<Long> orgIds = (List<Long>) checkR.getData();
        //todo 需要修改薪资组逻辑
       // List<Long> salaryGroupIds = (List<Long>) redisTemplate.boundValueOps("SalaryPermission" + userId).get();
        List<String> stringList= (List<String>) userController.getSalaryByUserId(userId).getData();
        List<Long> salaryGroupIds=new ArrayList<>();
        for (String s:stringList){
            salaryGroupIds.add(Long.valueOf(s));
        }

        List<Long> orgIds = getSalaryOrgIds(salaryGroupIds);

        PageResult<SalaryBandEntity> pageResult = salaryBandService.queryPage(systemId, lineId, jobLevelId, orgIds, pageNum, pageSize);

        return R.ok(pageResult);

    }


    @GetMapping("/findSalaryByOid/{oid}")
    @ApiOperation(value = "查询员工薪酬")
//    @PreAuthorize("hasAuthority('emp:salary:get')")
    public R<SalaryDto> findSalaryByOid(@PathVariable("oid") Long oid, HttpServletRequest request) throws Exception {
        EmployeeInfoEntity infoEntity = employeeInfoService.getByIdE(oid);
        R checkR = loginController.checkOrgPermission(request, infoEntity.getUnitId(), true);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        SalaryDto salaryDto = new SalaryDto();
        salaryDto.setOid(infoEntity.getOid());
        salaryDto.setMonthlySalary(infoEntity.getMonthlySalary());
        salaryDto.setPerformance(infoEntity.getPerformance());
        return R.ok(salaryDto);
    }


    @PostMapping("/updateSalaryByOid")
    @ApiOperation(value = "修改员工薪酬")
    @SysAuthorityLog(value = "修改员工薪酬")
//    @PreAuthorize("hasAuthority('emp:salary:update')")
    public R updateSalaryByOid(@RequestBody @Valid SalaryDto salaryDto, HttpServletRequest request) throws Exception {
        BigDecimal monthlySalary = salaryDto.getMonthlySalary();
        BigDecimal performance = salaryDto.getPerformance();
        if (monthlySalary == null || performance == null) {
            return R.error("薪资不能为空");
        }

        EmployeeInfoEntity entity = employeeInfoService.getByIdE(salaryDto.getOid());
        //判断是否为有该公司的权限
        R checkR = loginController.checkOrgPermission(request, entity.getUnitId(), true);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(salaryDto, EmployeeInfoEntity.class);

        return employeeInfoService.updateByIdE(employeeInfoEntity);
    }


    @GetMapping("/findAllsalaryGroup")
    @ApiOperation(value = "查询所有薪资组")
    public R<List<SalaryGroupDto>> findAllsalaryGroup() {
        List<SalaryGroupDto> group = jobController.salaryGroupMap.get("salaryGroupMap");


        return R.ok(group);

    }

    @GetMapping("/findSalaryUnit")
    @ApiOperation(value = "查询发薪单位")
    public R<List<SalaryPayrollUnitDto>> findSalaryUnit(@RequestParam(value = "cname", required = false) String cname,
                                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        Page<SalaryPayrollUnitDto> page = new Page<SalaryPayrollUnitDto>(pageNum, pageSize);
        List<Map<String, Object>> SalaryPayrollUnitDtoMap = new ArrayList<>();
//        ssqlSalaryGoupDao.getSalaryUnitByNamePage(cname, page);
        List<SalaryPayrollUnitDto> salaryUnitDtoArrayList = EntityUtil.ListMapToListObj(SalaryPayrollUnitDtoMap, SalaryPayrollUnitDto.class);
        if (CollectionUtils.isEmpty(salaryUnitDtoArrayList)) {
            return R.error("查询结果为空");
        }
        page.setRecords(salaryUnitDtoArrayList);
        return R.ok(new PageResult<SalaryPayrollUnitDto>(page));
    }


    @PostMapping("/updateEmployeeSalaryGroup")
    @ApiOperation(value = "分配、修改新员工薪资组")
    @SysAuthorityLog(value = "分配、修改新员工薪资组")
    @PreAuthorize("hasAuthority('emp:xzzfp:update')")
    public R updateSalaryGroup(@RequestBody @Valid SalaryGroupVo salaryGroupVo, HttpServletRequest request) throws Exception {
        //判断是否为有该公司的权限
        EmployeeInfoEntity entity = employeeInfoService.getByIdE(salaryGroupVo.getOid());
        R checkR = loginController.checkOrgPermission(request, entity.getUnitId(), true);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        //更新薪资组信息到员工信息表
        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(salaryGroupVo, EmployeeInfoEntity.class);
        employeeInfoEntity.setIsDistribute(1);

        return employeeInfoService.updateByIdE(employeeInfoEntity);
    }

    @PostMapping("/deleteSalaryDistribution")
    @ApiOperation(value = "删除员工薪资组")
    @SysAuthorityLog(value = "删除员工薪资组")
  // @PreAuthorize("hasAuthority('emp:xzzfp:update')")
    public R deleteSalaryDistribution(@RequestParam(value = "id") String id){
        salaryDistributionService.removeOneById(Long.valueOf(id));
        return R.ok();
    }

    @PostMapping("/findSalaryDistributionByOid")
    @ApiOperation(value = "根据oid查找员工薪资组")
    // @PreAuthorize("hasAuthority('emp:xzzfp:update')")
    public R findSalaryDistributionByOid(@RequestParam(value = "oid") String oid){

        EmployeeInfoEntity employeeInfoEntity= employeeInfoService.getByIdE(Long.valueOf(oid));
        List<com.zhangtai.Neusoft.vo.SalaryGroupVo> salaryGroupList= new ArrayList<>();
//                employeeBaseDao.getSalaryGroupList(employeeInfoEntity.getCode());
        JSONArray array=new JSONArray();
        if(!CollectionUtils.isEmpty(salaryGroupList)){
            for (com.zhangtai.Neusoft.vo.SalaryGroupVo salaryGroupVo:salaryGroupList){
                JSONObject object = new JSONObject();
                SalaryGroupDto salaryGroupDto = jobController.salaryGroupDtoMap.get(Long.parseLong(salaryGroupVo.getGroupId()));
                object.put("salaryGroupDto", salaryGroupDto);
                SalaryPayrollUnitDto salaryPayrollUnitDto = jobController.SalaryPayrollUnitMap.get(Long.parseLong(salaryGroupVo.getPayUnitId()));
                object.put("salaryPayrollUnitDto", salaryPayrollUnitDto);
                array.add(object);
            }
        }
        return R.ok(array);
    }



    @PostMapping("/logoutSalaryDistribution")
    @ApiOperation(value = "注销员工薪资组")
    @SysAuthorityLog(value = "注销员工薪资组")
    // @PreAuthorize("hasAuthority('emp:xzzfp:update')")
    public R logoutSalaryDistribution(@RequestBody @Valid SalaryGroupVo salaryGroupVo,
                                      HttpServletRequest request) throws Exception {

        //判断是否为有该公司的权限
        EmployeeInfoEntity entity = employeeInfoService.getByIdE(salaryGroupVo.getOid());
        R checkR = loginController.checkOrgPermission(request, entity.getUnitId(), true);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        JSONObject data = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return R.error("请先登录");
        }
        SalaryDistributionEntity salaryDistributionEntity = new SalaryDistributionEntity();
        salaryDistributionEntity.setIsDelete(0);
        salaryDistributionEntity.setSalaryGroupId(salaryGroupVo.getSalaryGroupId());
        salaryDistributionEntity.setPayrollUnitId(salaryGroupVo.getPayrollUnitId());
        salaryDistributionEntity.setRemark("");
        salaryDistributionEntity.setDistributionTime(salaryGroupVo.getDistributionTime());
        salaryDistributionEntity.setIsDistribute(1);
        salaryDistributionEntity.setDistributionName(data.getString("name"));
        salaryDistributionEntity.setDistributionCode(data.getString("usercode"));
        //因为是注销操作，所以旧薪资组及发薪单位都应该是当前传入的数据
        salaryDistributionEntity.setOidSalaryGroupId(salaryGroupVo.getSalaryGroupId());
        salaryDistributionEntity.setOidPayrollUnitId(salaryGroupVo.getPayrollUnitId());
        SalaryDistributionEntity salary = salaryDistributionDao.selectOne(new QueryWrapper<SalaryDistributionEntity>()
                    .eq("is_delete", 0).eq("oid", entity.getOid()));

        if (!ObjectUtils.isEmpty(salary)) {
                //更新薪资组表
                salaryDistributionEntity.setId(salary.getId());
                salaryDistributionEntity.setType(7); //待定
                salaryDistributionEntity.setUnitId(salary.getUnitId());
                salaryDistributionEntity.setOid(salary.getOid());
                salaryDistributionService.updateByIdE(salaryDistributionEntity);
        } else {
            //更新薪资组表
            salaryDistributionEntity.setOid(entity.getOid());
            //salaryDistributionEntity.setOrgId(entity.getOrgId());
            salaryDistributionEntity.setUnitId(entity.getUnitId());
            salaryDistributionEntity.setType(7);
            salaryDistributionEntity.setCreateTime(new Date());// 薪资组分配加上时间
            // salaryDistributionEntity.setCreateTime(salaryGroupVo.getCreateTime());
            salaryDistributionDao.insert(salaryDistributionEntity);
        }

        //同步注销薪资组信息到ehr 暂时注释
        List<Long> ids = new ArrayList<>();
        ids.add(salaryDistributionEntity.getId());
        neuEmployeeSalaryService.LogoutSalary(ids);

        //薪资组记录表
        SalaryDistributionRecordingEntity salaryDistributionRecordingEntity = BeanUtilsMabach.doToDto(salaryDistributionEntity, SalaryDistributionRecordingEntity.class);
        salaryDistributionRecordingEntity.setId(null);
        salaryDistributionRecordingService.saveE(salaryDistributionRecordingEntity);

        //更新变更后薪资组为null
        LambdaUpdateWrapper<SalaryDistributionEntity> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.set(SalaryDistributionEntity::getPayrollUnitId,null);
        updateWrapper.set(SalaryDistributionEntity::getSalaryGroupId,null);
        updateWrapper.eq(SalaryDistributionEntity::getId,salaryDistributionEntity.getId());
        salaryDistributionDao.update(null,updateWrapper );


        //更新薪资组信息到员工信息表
//        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(salaryGroupVo, EmployeeInfoEntity.class);
//        employeeInfoEntity.setSalaryGroupId(null);
//        employeeInfoEntity.setPayrollUnitId(null);
//        employeeInfoEntity.setIsDistribute(0);
//        employeeInfoService.updateByIdE(employeeInfoEntity);

        LambdaUpdateWrapper<EmployeeInfoEntity> update=new LambdaUpdateWrapper<>();
        update.set(EmployeeInfoEntity::getSalaryGroupId,null);
        update.set(EmployeeInfoEntity::getPayrollUnitId,null);
        update.set(EmployeeInfoEntity::getIsDistribute,0);
        update.eq(EmployeeInfoEntity::getOid,salaryGroupVo.getOid());
        employeeInfoDao.update(null,update );

        return R.ok();
    }




    @PostMapping("/updateSalaryDistribution")
    @ApiOperation(value = "新分配、修改新员工薪资组")
    @SysAuthorityLog(value = "新分配、修改新员工薪资组")
    @PreAuthorize("hasAuthority('emp:xzzfp:update')")
    public R updateSalaryDistribution(@RequestBody @Valid SalaryGroupVo salaryGroupVo, HttpServletRequest request) throws Exception {
        //判断是否为有该公司的权限
        EmployeeInfoEntity entity = employeeInfoService.getByIdE(salaryGroupVo.getOid());
        R checkR = loginController.checkOrgPermission(request, entity.getUnitId(), true);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        JSONObject data = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return R.error("请先登录");
        }
        boolean flag = false;
        SalaryDistributionEntity salaryDistributionEntity = new SalaryDistributionEntity();
        salaryDistributionEntity.setIsDelete(0);
        salaryDistributionEntity.setSalaryGroupId(salaryGroupVo.getSalaryGroupId());
        salaryDistributionEntity.setPayrollUnitId(salaryGroupVo.getPayrollUnitId());
        salaryDistributionEntity.setRemark(salaryGroupVo.getRemark());
        salaryDistributionEntity.setIsTax(salaryGroupVo.getIsTax());
        salaryDistributionEntity.setDistributionTime(salaryGroupVo.getDistributionTime());
        log.info(DateUtils.format(salaryGroupVo.getDistributionTime(), "YYYY-MM-DD"));
        salaryDistributionEntity.setIsDistribute(1);
        salaryDistributionEntity.setDistributionName(data.getString("name"));
        salaryDistributionEntity.setDistributionCode(data.getString("usercode"));
        if (salaryGroupVo.getId() == null) {
            SalaryDistributionEntity salary = salaryDistributionDao.selectOne(new QueryWrapper<SalaryDistributionEntity>()
                    .eq("is_delete", 0).eq("oid", entity.getOid()));
            if (!ObjectUtils.isEmpty(salary)) {
                if (0 == salary.getIsDistribute()) {
                    return R.error("已存在该员工薪资组分配信息");
                }
                if (1 == salary.getIsDistribute()) {
                    //更新薪资组表
                    salaryDistributionEntity.setId(salary.getId());
                    salaryDistributionEntity.setType(salary.getType());
                    // salaryDistributionEntity.setOrgId(salary.getOrgId());
                    salaryDistributionEntity.setUnitId(salary.getUnitId());
                    salaryDistributionEntity.setOid(salary.getOid());
                    salaryDistributionEntity.setOidSalaryGroupId(salary.getSalaryGroupId());
                    salaryDistributionEntity.setOidPayrollUnitId(salary.getPayrollUnitId());
                    salaryDistributionService.updateByIdE(salaryDistributionEntity);
                }
            } else {
                //更新薪资组表
                salaryDistributionEntity.setOid(salaryGroupVo.getOid());
                //salaryDistributionEntity.setOrgId(entity.getOrgId());
                salaryDistributionEntity.setUnitId(entity.getUnitId());
                salaryDistributionEntity.setType(salaryGroupVo.getType());
                // salaryDistributionEntity.setCreateTime(new Date());// 薪资组分配加上时间
                // salaryDistributionEntity.setCreateTime(salaryGroupVo.getCreateTime());
                salaryDistributionDao.insert(salaryDistributionEntity);
                flag = true;
            }
        } else {
            //更新薪资组表
            salaryDistributionEntity.setId(salaryGroupVo.getId());
            SalaryDistributionEntity distributionEntity = salaryDistributionService.getByIdE(salaryGroupVo.getId());
            salaryDistributionEntity.setType(distributionEntity.getType());
            // salaryDistributionEntity.setOrgId(distributionEntity.getOrgId());
            salaryDistributionEntity.setUnitId(distributionEntity.getUnitId());
            salaryDistributionEntity.setOid(distributionEntity.getOid());
            salaryDistributionEntity.setOidSalaryGroupId(distributionEntity.getSalaryGroupId());
            salaryDistributionEntity.setOidPayrollUnitId(distributionEntity.getPayrollUnitId());
            salaryDistributionService.updateByIdE(salaryDistributionEntity);
        }

        //同步薪资组分配信息到ehr 暂时注释
        List<Long> ids = new ArrayList<>();
        ids.add(salaryDistributionEntity.getId());
        neuEmployeeSalaryService.saveSalaryGroup(ids);

        SalaryDistributionRecordingEntity salaryDistributionRecordingEntity = BeanUtilsMabach.doToDto(salaryDistributionEntity, SalaryDistributionRecordingEntity.class);
        salaryDistributionRecordingEntity.setId(null);
        salaryDistributionRecordingService.saveE(salaryDistributionRecordingEntity);
        //更新薪资组信息到员工信息表
        EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(salaryGroupVo, EmployeeInfoEntity.class);
        employeeInfoEntity.setIsDistribute(1);
        if (flag) {
//            neuEmployeeBaseInfoService.sendMq(salaryDistributionEntity, EmployeeInfoConst.EMPLOYEE_GET_SALARY_Z, "salaryDistributionEntity", false);
        }
        return employeeInfoService.updateByIdE(employeeInfoEntity);
    }


    @PostMapping("/findAllEmployeeSalaryGroup")
    @ApiOperation(value = "分页条件查询新员工薪资组分配表")
    @PreAuthorize("hasAuthority('emp:xzzfp:get')")
    public R<List<EmployeeSalaryGroupDto>> findAllEmployeeSalaryGroup(@RequestBody @Valid EmployeeSalaryQueryListVo employeeSalaryQueryListVo, HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        String code = userInfo.getString("usercode");
        PageResult<EmployeeInfoEntity> pageResult = employeeInfoService.queryPageIsDistribute(employeeSalaryQueryListVo.getIsDistribute(), orgIds, code,
                employeeSalaryQueryListVo.getPageNum(), employeeSalaryQueryListVo.getPageSize());
        ArrayList<EmployeeSalaryGroupDto> salaryGroupDtoArrayList = new ArrayList<>();
        List<EmployeeInfoEntity> list = pageResult.getList();
        if (CollectionUtils.isEmpty(list)) {
            return R.error("查询结果为空");
        }
        for (EmployeeInfoEntity employeeInfoEntity : list) {
            EmployeeSalaryGroupDto employeeSalaryGroupDto = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeSalaryGroupDto.class);
            Long orgId = employeeInfoEntity.getOrgId();
            String orgNameById = jobController.getOrgNameById(orgId);
            employeeSalaryGroupDto.setOrgname(orgNameById);
            Long unitId = employeeInfoEntity.getUnitId();
            String unitname = jobController.getOrgNameById(unitId);
            employeeSalaryGroupDto.setUnitname(unitname);
            Long jobId = employeeInfoEntity.getJobId();
            String jobName = jobController.getJobName(jobId);
            employeeSalaryGroupDto.setJobname(jobName);
            Long salaryGroupId = employeeInfoEntity.getSalaryGroupId();
//            SalaryGroupDto allsalaryGroupByid = findAllsalaryGroupByid(salaryGroupId);
            SalaryGroupDto salaryGroupDto = jobController.salaryGroupDtoMap.get(salaryGroupId);
            employeeSalaryGroupDto.setSalaryGroupDto(salaryGroupDto);
            salaryGroupDtoArrayList.add(employeeSalaryGroupDto);
        }
        PageResult<EmployeeSalaryGroupDto> employeeSalaryGroupDtoPageResult = new PageResult<>();
        employeeSalaryGroupDtoPageResult.setList(salaryGroupDtoArrayList);
        employeeSalaryGroupDtoPageResult.setCurrPage(pageResult.getCurrPage());
        employeeSalaryGroupDtoPageResult.setPageSize(pageResult.getPageSize());
        employeeSalaryGroupDtoPageResult.setTotalCount(pageResult.getTotalCount());
        employeeSalaryGroupDtoPageResult.setTotalPage(pageResult.getTotalPage());

        return R.ok(employeeSalaryGroupDtoPageResult);

    }


    @PostMapping("/getSalaryDistributionPage")
    @ApiOperation(value = "新分页条件查询新员工薪资组分配表")
    @PreAuthorize("hasAuthority('emp:xzzfp:get')")
    public R<List<EmployeeSalaryGroupDto>> getSalaryDistributionPage(@RequestBody @Valid EmployeeSalaryQueryListVo employeeSalaryQueryListVo, HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        Page<EmployeeSalaryGroupDto> page = new Page<EmployeeSalaryGroupDto>(employeeSalaryQueryListVo.getPageNum(), employeeSalaryQueryListVo.getPageSize());
        List<Map<String, Object>> salaryDistributionMap = salaryDistributionDao.getSalaryDistributionInfoList(
                orgIds,
                //getOrgUnitListJob(0,employeeSalaryQueryListVo.getOrgname()),
                getOrgUnitListJob(1, employeeSalaryQueryListVo.getUnitname()),
                getOrgUnitListJob(2, employeeSalaryQueryListVo.getJobname()),
                employeeSalaryQueryListVo.getName(),
                employeeSalaryQueryListVo.getCode(),
                employeeSalaryQueryListVo.getIsDistribute(),
                page);
        List<EmployeeSalaryGroupDto> salaryGroupDtoArrayList = EntityUtil.ListMapToListObj(salaryDistributionMap, EmployeeSalaryGroupDto.class);
        if (CollectionUtils.isEmpty(salaryGroupDtoArrayList)) {
            return R.error("查询结果为空");
        }
        for (EmployeeSalaryGroupDto employeeSalaryGroupDto : salaryGroupDtoArrayList) {
            Long orgId = employeeSalaryGroupDto.getOrgId();
            String orgNameById = jobController.getOrgNameById(orgId);
            employeeSalaryGroupDto.setOrgname(orgNameById);
            Long unitId = employeeSalaryGroupDto.getUnitId();
            String unitname = jobController.getOrgNameById(unitId);
            employeeSalaryGroupDto.setUnitname(unitname);
            Long jobId = employeeSalaryGroupDto.getJobId();
            String jobName = jobController.getJobName(jobId);
            employeeSalaryGroupDto.setJobname(jobName);
            Long salaryGroupId = employeeSalaryGroupDto.getSalaryGroupId();
            SalaryGroupDto salaryGroupDto = jobController.salaryGroupDtoMap.get(salaryGroupId);
            employeeSalaryGroupDto.setSalaryGroupDto(salaryGroupDto);
            Long oidSalaryGroupId = employeeSalaryGroupDto.getOidSalaryGroupId();
            SalaryGroupDto oidSalaryGroupDto = jobController.salaryGroupDtoMap.get(oidSalaryGroupId);
            employeeSalaryGroupDto.setOidSalaryGroupDto(oidSalaryGroupDto);

            Long salaryUnitId = employeeSalaryGroupDto.getPayrollUnitId();
            SalaryPayrollUnitDto salaryPayrollUnitDto = jobController.SalaryPayrollUnitMap.get(salaryUnitId);
            employeeSalaryGroupDto.setSalaryUnitDto(salaryPayrollUnitDto);
            Long oidSalaryUnitId = employeeSalaryGroupDto.getOidPayrollUnitId();
            SalaryPayrollUnitDto oidSalaryPayrollUnitDto = jobController.SalaryPayrollUnitMap.get(oidSalaryUnitId);
            employeeSalaryGroupDto.setOidSalaryUnitDto(oidSalaryPayrollUnitDto);

        }

        page.setRecords(salaryGroupDtoArrayList);
        return R.ok(new PageResult<EmployeeSalaryGroupDto>(page));

    }


    @PostMapping("/getSalaryDistributionRecordingPage")
    @ApiOperation(value = "新分页条件查询新员工薪资组分配记录表")
    @PreAuthorize("hasAuthority('emp:xzzfp:get')")
    public R<List<EmployeeSalaryGroupDto>> getSalaryDistributionRecordingPage(@RequestBody @Valid EmployeeSalaryQueryListVo employeeSalaryQueryListVo, HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        List<Map<String, Object>> SalaryDistributionRecordingMap = salaryDistributionRecordingService.queryPageList(
                orgIds,
                getOrgUnitListJob(0, employeeSalaryQueryListVo.getOrgname()),
                getOrgUnitListJob(1, employeeSalaryQueryListVo.getUnitname()),
                getOrgUnitListJob(2, employeeSalaryQueryListVo.getJobname()),
                DateUtils.formatYM(employeeSalaryQueryListVo.getDistributionTime()),
                employeeSalaryQueryListVo.getName(),
                employeeSalaryQueryListVo.getCode(),
                employeeSalaryQueryListVo.getPageNum(),
                employeeSalaryQueryListVo.getPageSize());
        List<EmployeeSalaryGroupDto> salaryGroupDtoArrayList = EntityUtil.ListMapToListObj(SalaryDistributionRecordingMap, EmployeeSalaryGroupDto.class);
        if (CollectionUtils.isEmpty(salaryGroupDtoArrayList)) {
            return R.error("查询结果为空");
        }
        for (EmployeeSalaryGroupDto employeeSalaryGroupDto : salaryGroupDtoArrayList) {
            Long orgId = employeeSalaryGroupDto.getOrgId();
            String orgNameById = jobController.getOrgNameById(orgId);
            employeeSalaryGroupDto.setOrgname(orgNameById);
            Long unitId = employeeSalaryGroupDto.getUnitId();
            String unitname = jobController.getOrgNameById(unitId);
            employeeSalaryGroupDto.setUnitname(unitname);
            Long jobId = employeeSalaryGroupDto.getJobId();
            String jobName = jobController.getJobName(jobId);
            employeeSalaryGroupDto.setJobname(jobName);
            Long salaryGroupId = employeeSalaryGroupDto.getSalaryGroupId();
            SalaryGroupDto salaryGroupDto = jobController.salaryGroupDtoMap.get(salaryGroupId);
            employeeSalaryGroupDto.setSalaryGroupDto(salaryGroupDto);
            Long oidSalaryGroupId = employeeSalaryGroupDto.getOidSalaryGroupId();
            SalaryGroupDto oidSalaryGroupDto = jobController.salaryGroupDtoMap.get(oidSalaryGroupId);
            employeeSalaryGroupDto.setOidSalaryGroupDto(oidSalaryGroupDto);

            Long salaryUnitId = employeeSalaryGroupDto.getPayrollUnitId();
            SalaryPayrollUnitDto salaryPayrollUnitDto = jobController.SalaryPayrollUnitMap.get(salaryUnitId);
            employeeSalaryGroupDto.setSalaryUnitDto(salaryPayrollUnitDto);
            Long oidSalaryUnitId = employeeSalaryGroupDto.getOidPayrollUnitId();
            SalaryPayrollUnitDto oidSalaryPayrollUnitDto = jobController.SalaryPayrollUnitMap.get(oidSalaryUnitId);
            employeeSalaryGroupDto.setOidSalaryUnitDto(oidSalaryPayrollUnitDto);
        }

        Page page = new Page(employeeSalaryQueryListVo.getPageNum(), employeeSalaryQueryListVo.getPageSize());
        page.setRecords(salaryGroupDtoArrayList);
        return R.ok(new PageResult<EmployeeSalaryGroupDto>(page));

    }

    @GetMapping("/findEmployeeSalaryGroupById/{oid}")
    @ApiOperation(value = "根据员工id查询员工--薪资组分配")
    @PreAuthorize("hasAuthority('emp:xzzfp:get')")
    public R findEmployeeSalaryGroupById(@PathVariable("oid") Long oid, HttpServletRequest request) throws Exception {
        EmployeeInfoEntity byIdE = employeeInfoService.getByIdE(oid);
        if (ObjectUtils.isEmpty(byIdE)) {
            return R.error("查询结果为空");
        }
        R checkR = loginController.checkOrgPermission(request, byIdE.getUnitId(), true);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        JSONObject object = new JSONObject();
        Long salaryGroupId = byIdE.getSalaryGroupId();
        SalaryGroupDto salaryGroupDto = jobController.salaryGroupDtoMap.get(salaryGroupId);
        object.put("salaryGroupDto", salaryGroupDto);
        SalaryPayrollUnitDto salaryPayrollUnitDto = jobController.SalaryPayrollUnitMap.get(byIdE.getPayrollUnitId());
        object.put("salaryPayrollUnitDto", salaryPayrollUnitDto);
        return R.ok(object);

    }


    @GetMapping("/getEmployeeSalaryBandMonitoring")
    @ApiOperation(value = "分页查询员工--薪资带宽监控表")
    @PreAuthorize("hasAuthority('emp:xzkdjk:get')")
    public R<PageResult<EmployeeSalaryBandMonitoringDto>> getEmployeeSalaryBandMonitoring(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                                          @RequestParam(value = "keyword", required = false) String keyword,
                                                                                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
//        List<Long> orgIds = (List<Long>) checkR.getData();
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        String id = userInfo.getString("id");

        // todo 需要修改薪资组逻辑
      //  List<Long> salaryGroupIds = (List<Long>) redisTemplate.boundValueOps("SalaryPermission" + id).get();

        List<String> stringList= (List<String>) userController.getSalaryByUserId(id).getData();
        List<Long> salaryGroupIds=new ArrayList<>();
        for (String s:stringList){
            salaryGroupIds.add(Long.valueOf(s));
        }
        List<Long> orgIds = getSalaryOrgIds(salaryGroupIds);

        PageResult<EmployeeInfoEntity> pageResult = employeeInfoService.findBySalaryBran(keyword, orgIds, null, pageNum, pageSize);
        List<EmployeeInfoEntity> list = pageResult.getList();
        ArrayList<EmployeeSalaryBandMonitoringDto> dtoArrayList = new ArrayList<>();
        for (EmployeeInfoEntity employeeInfoEntity : list) {
            EmployeeSalaryBandMonitoringDto bandMonitoringDto = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeSalaryBandMonitoringDto.class);
            Long jobId = bandMonitoringDto.getJobId();
            Long jobSystemId = bandMonitoringDto.getJobSystemId();
            Long lineId = bandMonitoringDto.getLineId();
            Long orgId = bandMonitoringDto.getOrgId();
            Long unitId = bandMonitoringDto.getUnitId();

            BigDecimal monthlySalary = bandMonitoringDto.getMonthlySalary();
            Long jobLevelId = bandMonitoringDto.getJobLevelId();

            String jobName = jobController.getJobName(jobId);
            String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
            String orgNameById = jobController.getOrgNameById(orgId);
            String unitName = jobController.getOrgNameById(unitId);
            bandMonitoringDto.setJobname(jobName);
            bandMonitoringDto.setJobLevel(jobLevelNameById);
            bandMonitoringDto.setOrgname(orgNameById);
            bandMonitoringDto.setUnitname(unitName);
            String systemNameById = jobController.getSystemNameById(jobSystemId);
            String lineNameById = jobController.getLineNameById(lineId);
            bandMonitoringDto.setJobSystem(systemNameById);
            bandMonitoringDto.setLine(lineNameById);

            BigDecimal bandSalary3th = salaryBandService.findByParam(jobSystemId, lineId, jobLevelId);
            bandMonitoringDto.setBandSalaryimit(bandSalary3th);

            if (bandSalary3th != null && monthlySalary != null) {
                BigDecimal diff = monthlySalary.subtract(bandSalary3th);
                bandMonitoringDto.setDifferenceSalary(diff);
                bandMonitoringDto.setIncreaseValueRate(diff.divide(bandSalary3th, 2, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP));

            }


            dtoArrayList.add(bandMonitoringDto);


        }

        PageResult<EmployeeSalaryBandMonitoringDto> dtoPageResult = new PageResult<>();
        dtoPageResult.setList(dtoArrayList);
        dtoPageResult.setTotalPage(pageResult.getTotalPage());
        dtoPageResult.setTotalCount(pageResult.getTotalCount());
        dtoPageResult.setPageSize(pageResult.getPageSize());
        dtoPageResult.setCurrPage(pageResult.getCurrPage());

        return R.ok(dtoPageResult);

    }


    @DeleteMapping("/deleteSalaryBandMonitoring/{id}")
    @ApiOperation(value = "删除员工--薪资带宽监控表")
    @SysAuthorityLog(value = "删除员工--薪资带宽监控表")
    @PreAuthorize("hasAuthority('emp:xzkdjk:get')")
    public R deleteSalaryBandMonitoring(@PathVariable("id") Long id, HttpServletRequest request) throws Exception {
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(id);
        //判断是否为有该公司的权限
        R checkR = loginController.checkOrgPermission(request, employeeInfoEntity.getUnitId(), true);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        return employeeInfoService.deleteSalaryBandMonitoring(id);

    }

    @GetMapping("/findEmployeeSalaryBandMonitoringByid/{id}")
    @ApiOperation(value = "根据员工id查询新员工--薪资带宽监控表")
    @PreAuthorize("hasAuthority('emp:xzkdjk:get')")
    public R<EmployeeSalaryBandMonitoringDto> findEmployeeSalaryBandMonitoringByid(@PathVariable("id") Long id,
                                                                                   HttpServletRequest request) throws Exception {
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(id);
        //判断是否为有该公司的权限
        R checkR = loginController.checkOrgPermission(request, employeeInfoEntity.getUnitId(), true);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        EmployeeSalaryBandMonitoringDto bandMonitoringDto = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeSalaryBandMonitoringDto.class);
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.ok();
        }
        Long jobId = employeeInfoEntity.getJobId();
        Long jobSystemId = employeeInfoEntity.getJobSystemId();
        Long lineId = employeeInfoEntity.getLineId();
//            Long managementJoblevelId = bandMonitoringDto.getManagementJoblevelId();
//            Long professionJoblevelId = bandMonitoringDto.getProfessionJoblevelId();
        Long jobLevelId = employeeInfoEntity.getJobLevelId();
        BigDecimal monthlySalary = employeeInfoEntity.getMonthlySalary();

//        log.info("jobId:{}",jobId);
//        log.info("jobSystemId:{}",jobSystemId);
//        log.info("lineId:{}",lineId);
//        log.info("jobLevelId:{}",jobLevelId);
//        log.info("monthlySalary:{}",monthlySalary);
        BigDecimal bandSalary3th = salaryBandService.findByParam(jobSystemId, lineId, jobLevelId);
        bandMonitoringDto.setBandSalaryimit(bandSalary3th);

        BigDecimal diff = null;
        if (bandSalary3th != null) {
//                diff = bandSalary3th.subtract(monthlySalary).setScale(0, BigDecimal.ROUND_HALF_UP);
            diff = monthlySalary.subtract(bandSalary3th);
            bandMonitoringDto.setIncreaseValueRate(diff.divide(bandSalary3th, 2, BigDecimal.ROUND_HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP));
        }


        bandMonitoringDto.setDifferenceSalary(diff);


        return R.ok(bandMonitoringDto);

    }

    @PostMapping("/updateTransferSalaryGroup")
    @ApiOperation(value = "分配、修改员工异动的薪资组组")
    @SysAuthorityLog(value = "分配、修改员工异动的薪资组组")
    @Transactional
    @PreAuthorize("hasAuthority('emp:xzzfp:updatee')")
    public R updateTransfer(@RequestBody @Valid SalaryGroupVo salaryGroupVo, HttpServletRequest request) throws Exception {
        Boolean flag = false;

        TransferInfoEntity transferInfoEntity = BeanUtilsMabach.doToDto(salaryGroupVo, TransferInfoEntity.class);

        transferInfoEntity.setIsDistribute(1);//是否分配了薪资组 薪资组分配情况，0:未分配，1：已分配
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(salaryGroupVo.getOid());
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.error("根据oid查询员工为空");
        }
        //判断是否为有该公司的权限
        R checkR = loginController.checkOrgPermission(request, employeeInfoEntity.getUnitId(), true);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        employeeInfoEntity.setIsDistribute(1); //是否分配了薪资组 薪资组分配情况，0:未分配，1：已分配
        employeeInfoEntity.setSalaryGroupId(salaryGroupVo.getSalaryGroupId());
        transferInfoService.updateByIdE(transferInfoEntity);
        employeeInfoService.updateByIdE(employeeInfoEntity);
        flag = true;

        if (flag) {
            return R.ok();
        }
        return R.error();


    }

    @GetMapping("/getTransferSalaryGroupList")
//    @DataSource("slave1")
    @ApiOperation(value = "分页查询员工异动薪资组列表")
    @PreAuthorize("hasAuthority('emp:xzzfp:get')")
    public R<PageResult<TransferSalaryGroupDto>> getTransferSalaryGroupList(@ApiParam(value = "是否已分配，0:未分配，1：已分配", required = false) @RequestParam(value = "isDistribute", required = false) Integer isDistribute,
                                                                            @RequestParam(value = "keyword", required = false) String keyword,
                                                                            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                                            HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        PageResult<TransferInfoEntity> pageResult = transferInfoService.queryPage(isDistribute, keyword, orgIds, pageNum, pageSize);
        List<TransferInfoEntity> pageResultList = pageResult.getList();
        if (CollectionUtils.isEmpty(pageResultList)) {
            return R.ok();
        }
        ArrayList<TransferSalaryGroupDto> groupDtoArrayList = new ArrayList<>();
        for (TransferInfoEntity transferInfoEntity : pageResultList) {
            Long sid = 0l;
            TransferSalaryGroupDto transferSalaryGroupDto = BeanUtilsMabach.doToDto(transferInfoEntity, TransferSalaryGroupDto.class);
            List<Long> oldSalaryGroupId = new ArrayList<>();
//            ssqlSalaryGoupDao.getOldSalaryGroupId(transferSalaryGroupDto.getOid());
            if (oldSalaryGroupId.size() >= 2) {
                sid = oldSalaryGroupId.get(1);
            }
            if (oldSalaryGroupId.size() == 1) {
                sid = oldSalaryGroupId.get(0);
            }
            Long salaryGroupId = transferInfoEntity.getSalaryGroupId(); //获取现在工资组id
            if (salaryGroupId == null) {
                return R.error("查询工资组id为空");
            }

            SalaryGroupDto oldGroup = new SalaryGroupDto();
//                    ssqlSalaryGoupDao.getSalaryGroupById(sid);// 获取原工资组
            SalaryGroupDto salaryGroupNew = new SalaryGroupDto();
//            ssqlSalaryGoupDao.getSalaryGroupById(salaryGroupId); //获取现在工资组
            transferSalaryGroupDto.setOldSalaryGroupDto(oldGroup);
            transferSalaryGroupDto.setSalaryGroupDto(salaryGroupNew);
            groupDtoArrayList.add(transferSalaryGroupDto);

        }

        PageResult<TransferSalaryGroupDto> transferSalaryGroupDtoPageResult = new PageResult<>();
        transferSalaryGroupDtoPageResult.setList(groupDtoArrayList);
        transferSalaryGroupDtoPageResult.setTotalPage(pageResult.getTotalPage());
        transferSalaryGroupDtoPageResult.setTotalCount(pageResult.getTotalCount());
        transferSalaryGroupDtoPageResult.setPageSize(pageResult.getPageSize());
        transferSalaryGroupDtoPageResult.setCurrPage(pageResult.getCurrPage());


        return R.ok(transferSalaryGroupDtoPageResult);

    }


    @GetMapping("/getUserBankCardChangeNumber")
    @ApiOperation(value = "查询员工工资卡异动数")
    @PreAuthorize("hasAuthority('emp:gzk:get')")
    public R getUserBankCardChangeNumber(HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        Integer Number = userBankCardDao.getUserBankCardChangeNumber(orgIds);
        return R.ok(Number);
    }

    @GetMapping("/updateUserBankCardStatus")
    @ApiOperation(value = "修改工资卡异动状态")
    @SysAuthorityLog(value = "修改工资卡异动状态")
    @PreAuthorize("hasAuthority('emp:gzk:update')")
    public R updateUserBankCardStatus(@RequestParam("id") String id, @RequestParam("status") Integer status,
                                      @RequestParam(value = "remark", required = false) String remark) {
        UserBankCardEntity userBankCardEntity = userBankCardService.getByIdE(Long.valueOf(id));
        userBankCardEntity.setStatus(status);
        if (!StringUtils.isEmpty(remark)) {
            userBankCardEntity.setRemark(remark);
        }
        userBankCardDao.updateById(userBankCardEntity);
        //改工资卡异动待办为已办
        noticeController.updateNoticeTodo(Long.valueOf(id), NoticeConst.TODO_TYPE_CARD_CHANGE);
        return R.ok();
    }

    /**
     * 列表
     */
    @GetMapping("/getUserBankCardPage")
    @ApiOperation(value = "分页工资卡异动列表")
    @PreAuthorize("hasAuthority('emp:gzk:get')")
    public R getUserBankCardPage(@RequestParam(value = "createName", required = false) String createName,
                                 @RequestParam(value = "code", required = false) String code,
                                 @RequestParam(value = "orgname", required = false) String orgname,
                                 @RequestParam(value = "unitname", required = false) String unitname,
                                 @RequestParam(value = "jobname", required = false) String jobname,
                                 @RequestParam(value = "status", required = false) Integer status,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        Page<UserBankCardDto> page = new Page<UserBankCardDto>(pageNum, pageSize);
        List<UserBankCardDto> recordList = userBankCardService.getUserBankCardPage(orgIds,
                createName, code, orgname, unitname, jobname, status, page);
        for (UserBankCardDto userBankCardDto : recordList) {
            if (userBankCardDto.getJobId() != null && StringUtils.isEmpty(userBankCardDto.getJobname()))
                userBankCardDto.setJobname(jobController.getJobName(userBankCardDto.getJobId()));
            if (userBankCardDto.getOrgId() != null && StringUtils.isEmpty(userBankCardDto.getOrgname()))
                userBankCardDto.setOrgname(jobController.getOrgNameById(userBankCardDto.getOrgId()));
            if (userBankCardDto.getUid() != null && StringUtils.isEmpty(userBankCardDto.getUnitname()))
                userBankCardDto.setUnitname(jobController.getOrgNameById(userBankCardDto.getUid()));
        }
        page.setRecords(recordList);
        return R.ok(new PageResult<UserBankCardDto>(page));
    }

    @GetMapping("/getUserBankCardRecordingPage")
    @ApiOperation(value = "分页工资卡异动记录列表")
    @PreAuthorize("hasAuthority('emp:gzk:get')")
    public R getUserBankCardRecordingPage(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        PageResult result = authorityLogService.queryPage(orgIds, null, null, null, "3", null, null, null, null, pageNum, pageSize);
        List<UserBankCardAnnalDto> UserBankCardAnnalDtoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(result.getList())) {
            List<AuthorityLogEntity> authorityLogEntityList = result.getList();
            for (AuthorityLogEntity authorityLogEntity : authorityLogEntityList) {
                UserBankCardEntity userBankCard = JSONObject.parseObject(authorityLogEntity.getParams(), UserBankCardEntity.class);
                UserBankCardAnnalDto userBankCardAnnalDto = BeanUtilsMabach.doToDto(userBankCard, UserBankCardAnnalDto.class);
                userBankCardAnnalDto.setInvalidDate(authorityLogEntity.getUpdateTime());
                UserBankCardAnnalDtoList.add(userBankCardAnnalDto);
            }
        }
        Page page = new Page(pageNum, pageSize);
        page.setRecords(UserBankCardAnnalDtoList);
        return R.ok(new PageResult<UserBankCardAnnalDto>(page));
    }


    /**
     * 列表
     */
    @GetMapping("/getAwardApplicantPage")
    @ApiOperation(value = "分页查询薪资奖罚列表")
    @PreAuthorize("hasAuthority('emp:jffp:get')")
    public R getAwardApplicantPage(@RequestParam(value = "applicantName", required = false) String applicantName,
                                   @RequestParam(value = "awardName", required = false) String awardName,
                                   @RequestParam(value = "usercode", required = false) String usercode,
                                   @RequestParam(value = "startTime", required = false) String startTime,
                                   @RequestParam(value = "endTime", required = false) String endTime,
                                   @RequestParam(value = "approvalStatus") Integer approvalStatus,
                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        Page page = new Page(pageNum, pageSize);
        List<AwardApplicantEntity> awardApplicantEntityList = awardApplicantDao.getAwardApplicantPage(orgIds, awardName, applicantName, usercode, StringUtils.isEmpty(startTime) ? startTime : startTime + " 00:00:00", StringUtils.isEmpty(endTime) ? endTime : endTime + " 23:59:59", approvalStatus, page);
        page.setRecords(awardApplicantEntityList);
        return R.ok(new PageResult<AwardApplicantEntity>(page));
    }

    /**
     * 列表
     */
    @GetMapping("/getSalaryChangePage")
    @ApiOperation(value = "分页查询薪资调整列表")
    @PreAuthorize("hasAuthority('emp:xztz:get')")
    public R getSalaryChangePage(@RequestParam(value = "name", required = false) String name,
                                 @RequestParam(value = "orgname", required = false) String orgName,
                                 @RequestParam(value = "unitname", required = false) String unitName,
                                 @RequestParam(value = "code", required = false) String code,
                                 @RequestParam(value = "type", required = false) Integer type,
                                 @RequestParam(value = "approveStatus", required = false) Integer approveStatus,
                                 @RequestParam(value = "status", required = false) Integer status,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        //改为薪资权限
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        String id = userInfo.getString("id");
        String applyCode = userInfo.getString("usercode");

      //  List<Long> salaryGroupIds = (List<Long>) redisTemplate.boundValueOps("SalaryPermission" + id).get();
        List<String> stringList= (List<String>) userController.getSalaryByUserId(id).getData();
        List<Long> salaryGroupIds=new ArrayList<>();
        for (String s:stringList){
            salaryGroupIds.add(Long.valueOf(s));
        }
//        List<Long> orgIds = getSalaryOrgIds(salaryGroupIds);

        Page<SalaryChangeDto> page = new Page<SalaryChangeDto>(pageNum, pageSize);
        List<SalaryChangeDto> salaryChangeList = salaryChangeDao.getSalaryChangeList(orgIds, name, orgName, unitName, code, applyCode, type, approveStatus, status, page);

        for (SalaryChangeDto salaryChangeDto : salaryChangeList) {
            if (salaryChangeDto.getJobId() != null && StringUtils.isEmpty(salaryChangeDto.getJobname()))
                salaryChangeDto.setJobname(jobController.getJobName(salaryChangeDto.getJobId()));
            if (salaryChangeDto.getOrgId() != null && StringUtils.isEmpty(salaryChangeDto.getOrgname()))
                salaryChangeDto.setOrgname(jobController.getOrgNameById(salaryChangeDto.getOrgId()));
            if (salaryChangeDto.getUnitId() != null && StringUtils.isEmpty(salaryChangeDto.getUnitname()))
                salaryChangeDto.setUnitname(jobController.getOrgNameById(salaryChangeDto.getUnitId()));

            if (salaryChangeDto.getNewJobId() != null && StringUtils.isEmpty(salaryChangeDto.getNewJobName()))
                salaryChangeDto.setNewJobName(jobController.getJobName(salaryChangeDto.getNewJobId()));
            if (salaryChangeDto.getNewOrgId() != null && StringUtils.isEmpty(salaryChangeDto.getNewOrgName()))
                salaryChangeDto.setNewOrgName(jobController.getOrgNameById(salaryChangeDto.getNewOrgId()));
            if (salaryChangeDto.getNewUnitId() != null && StringUtils.isEmpty(salaryChangeDto.getNewUnitName()))
                salaryChangeDto.setNewUnitName(jobController.getOrgNameById(salaryChangeDto.getNewUnitId()));
        }
        page.setRecords(salaryChangeList);
        return R.ok(new PageResult<SalaryChangeDto>(page));
    }

    /**
     * 列表
     */
    @GetMapping("/getSalaryChangeConfirmPage")
    @ApiOperation(value = "分页查询薪资调整列表")
    @PreAuthorize("hasAuthority('emp:xztz:get')")
    public R getSalaryChangeConfirmPage(@RequestParam(value = "name", required = false) String name,
                                 @RequestParam(value = "orgname", required = false) String orgName,
                                 @RequestParam(value = "unitname", required = false) String unitName,
                                 @RequestParam(value = "code", required = false) String code,
                                 @RequestParam(value = "type", required = false) Integer type,
                                 @RequestParam(value = "approveStatus", required = false) Integer approveStatus,
                                 @RequestParam(value = "status", required = false) Integer status,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        //改为薪资权限
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        String id = userInfo.getString("id");
        String applyCode = userInfo.getString("usercode");

       // List<Long> salaryGroupIds = (List<Long>) redisTemplate.boundValueOps("SalaryPermission" + id).get();
        List<String> stringList= (List<String>) userController.getSalaryByUserId(id).getData();
        List<Long> salaryGroupIds=new ArrayList<>();
        for (String s:stringList){
            salaryGroupIds.add(Long.valueOf(s));
        }
//        List<Long> orgIds = getSalaryOrgIds(salaryGroupIds);
        if(ObjectUtils.isEmpty(salaryGroupIds)){
            return R.error("请先设置薪资组再查询！");
        }
        Page<SalaryChangeDto> page = new Page<SalaryChangeDto>(pageNum, pageSize);
        List<SalaryChangeDto> salaryChangeList = salaryChangeDao.getSalaryChangeConfirmList(salaryGroupIds, name, orgName, unitName, code, applyCode, type, approveStatus, status, page);

        for (SalaryChangeDto salaryChangeDto : salaryChangeList) {
            if (salaryChangeDto.getJobId() != null && StringUtils.isEmpty(salaryChangeDto.getJobname()))
                salaryChangeDto.setJobname(jobController.getJobName(salaryChangeDto.getJobId()));
            if (salaryChangeDto.getOrgId() != null && StringUtils.isEmpty(salaryChangeDto.getOrgname()))
                salaryChangeDto.setOrgname(jobController.getOrgNameById(salaryChangeDto.getOrgId()));
            if (salaryChangeDto.getUnitId() != null && StringUtils.isEmpty(salaryChangeDto.getUnitname()))
                salaryChangeDto.setUnitname(jobController.getOrgNameById(salaryChangeDto.getUnitId()));

            if (salaryChangeDto.getNewJobId() != null && StringUtils.isEmpty(salaryChangeDto.getNewJobName()))
                salaryChangeDto.setNewJobName(jobController.getJobName(salaryChangeDto.getNewJobId()));
            if (salaryChangeDto.getNewOrgId() != null && StringUtils.isEmpty(salaryChangeDto.getNewOrgName()))
                salaryChangeDto.setNewOrgName(jobController.getOrgNameById(salaryChangeDto.getNewOrgId()));
            if (salaryChangeDto.getNewUnitId() != null && StringUtils.isEmpty(salaryChangeDto.getNewUnitName()))
                salaryChangeDto.setNewUnitName(jobController.getOrgNameById(salaryChangeDto.getNewUnitId()));
        }
        page.setRecords(salaryChangeList);
        return R.ok(new PageResult<SalaryChangeDto>(page));
    }


    /**
     * 删除薪资调整数据
     */
    @DeleteMapping("deleteSalaryChange")
    @ApiOperation(value = "删除薪资调整信息")
    @SysAuthorityLog(value = "删除薪资调整信息")
    @Transactional
    public R deleteSalaryChange(@RequestParam(value = "id") String id) {
        salaryChangeDao.deleteById(Long.valueOf(id));
        return R.ok();
    }

    /**
     * 保存
     */
    @PostMapping("/saveAndUpdateSalaryChange")
    @ApiOperation(value = "保存/修改薪资调整信息")
    @SysAuthorityLog(value = "保存/修改薪资变动信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:xztz:update')")
    public R saveAwardInfo(@RequestBody @Valid SalaryChangeVo salaryChangeVo, HttpServletRequest request) throws Exception {

        Long id = snowflakeIdWorker.nextId();
        JSONObject data = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return R.error("请先登录");
        }
        SalaryChangeEntity salaryChangeEntity = BeanUtilsMabach.doToDto(salaryChangeVo, SalaryChangeEntity.class);
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(salaryChangeVo.getOid());
        salaryChangeEntity.setEffectiveTime(salaryChangeEntity.getApplyTime());
        if (!CollectionUtils.isEmpty(salaryChangeVo.getFileUrls())) {
            saveFile(employeeInfoEntity.getOid(), salaryChangeVo.getFileUrls(), "薪资变动附件", 22);
        }
        salaryChangeEntity.setFileUrl(CollectionUtils.isEmpty(salaryChangeVo.getFileUrls()) ? "" : ListToString(salaryChangeVo.getFileUrls()));
        R r;
        if (salaryChangeEntity.getId() == null) {
            salaryChangeEntity.setId(id);
//            salaryChangeEntity.setOrgId(employeeInfoEntity.getOrgId());
            salaryChangeEntity.setUnitId(employeeInfoEntity.getUnitId());
            salaryChangeEntity.setApplyCode(data.getString("usercode"));
            salaryChangeEntity.setApplyName(data.getString("name"));
            salaryChangeEntity.setApproveStatus(0);
            salaryChangeEntity.setCreateTime(new Date());
            salaryChangeEntity.setIsDelete(0);
            salaryChangeEntity.setStatus(0);
            salaryChangeEntity.setNewJobId(employeeInfoEntity.getJobId());
            salaryChangeEntity.setNewOrgId(employeeInfoEntity.getOrgId());
            salaryChangeEntity.setNewUnitId(employeeInfoEntity.getUnitId());
            salaryChangeEntity.setNewJobLevel(employeeInfoEntity.getJobLevel());
            salaryChangeEntity.setNewJobLevelId(employeeInfoEntity.getJobLevelId());
            salaryChangeEntity.setNewJobLevelType(employeeInfoEntity.getJobLevelType());
            r = salaryChangeService.saveE(salaryChangeEntity);
        } else {
            r = salaryChangeService.updateByIdE(salaryChangeEntity);
            //修改薪资变动待办为已办
            noticeController.updateNoticeTodo(salaryChangeVo.getId(), NoticeConst.TODO_TYPE_SALARY_CONFIRM);
            if (1 == salaryChangeVo.getStatus()) {
//                neuEmployeeBaseInfoService.saveSalary(salaryChangeEntity.getId());
            }
        }
        return r;
    }


    /**
     * 信息
     */
    @GetMapping("/getAwardInfoById/{id}")
    @ApiOperation(value = "根据id查看薪资奖罚详情")
    @PreAuthorize("hasAuthority('emp:jffp:get')")
    public R getAwardInfoById(@PathVariable("id") Long id) {
        AwardApplicantEntity awardApplicantEntity = awardApplicantService.getByIdE(id);
        AwardInfoDto awardInfoDto = BeanUtilsMabach.doToDto(awardApplicantEntity, AwardInfoDto.class);
        List<String> fileUrlList = new ArrayList<>();
        if (!StringUtils.isEmpty(awardApplicantEntity.getUrl())) {
            String[] UrlList = awardApplicantEntity.getUrl().split(",");
            fileUrlList = Arrays.asList(UrlList);
        }
        awardInfoDto.setFileUrlList(fileUrlList);
        List<AwardInfoEntity> awardInfoEntityList = awardInfoDao.getAwardInfoBySerialNum(awardInfoDto.getSerialNum());
        awardInfoDto.setList(awardInfoEntityList);
        return R.ok(awardInfoDto);
    }

    @GetMapping("/updateUserBankCard")
    @ApiOperation(value = "修改工资卡 部门")
    @Transactional
    public R updateUserBankCard() {
        List<UserBankCardEntity> userBankCardEntityList = userBankCardDao.selectList(new QueryWrapper<UserBankCardEntity>().eq("is_delete", 0));
        List<EmployeeInfoEntity> employeeInfoEntityList = new ArrayList<>();
        for (UserBankCardEntity userBankCardEntity : userBankCardEntityList) {
            EmployeeInfoEntity employeeInfoEntity = getEmployessInfoByCode(userBankCardEntity.getCreateCode());
            employeeInfoEntityList.add(employeeInfoEntity);
        }
//            if(!ObjectUtils.isEmpty(employeeInfoEntity)){
//                userBankCardEntity.setUnitId(employeeInfoEntity.getUnitId());
//                userBankCardService.updateByIdE(userBankCardEntity);
//            }


        return R.ok();
    }


    @GetMapping("/getAwardPackagePage")
    @ApiOperation(value = "分页查询薪资奖罚包信息")
    public R getAwardPackagePage(@RequestParam(value = "serialNum", required = false) String serialNum,
                                 @RequestParam(value = "applicantName", required = false) String applicantName,
                                 @RequestParam(value = "applyTimeStart", required = false) String applyTimeStart,
                                 @RequestParam(value = "applyTimeEnd", required = false) String applyTimeEnd,
                                 @RequestParam(value = "awardName", required = false) String awardName,
                                 @RequestParam(value = "distributionStatus", required = false) ArrayList<Integer> distributionStatus,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request
    ) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        PageResult result = awardPackageService.queryPage(orgIds, serialNum, applicantName, applyTimeStart, applyTimeEnd, awardName, distributionStatus, pageNum, pageSize);
        List<AwardPackageEntity> list = result.getList();
        List<AwardPackageDto> awardPackageDtoList = new ArrayList<>();
        for (AwardPackageEntity awardPackageEntity : list) {
            AwardPackageDto awardPackageDto = BeanUtilsMabach.doToDto(awardPackageEntity, AwardPackageDto.class);
            if (awardPackageDto.getJobId() != null && StringUtils.isEmpty(awardPackageDto.getJobname()))
                awardPackageDto.setJobname(jobController.getJobName(awardPackageDto.getJobId()));
            if (awardPackageDto.getOrgId() != null && StringUtils.isEmpty(awardPackageDto.getOrgname()))
                awardPackageDto.setOrgname(jobController.getOrgNameById(awardPackageDto.getOrgId()));
            if (awardPackageDto.getUnitId() != null && StringUtils.isEmpty(awardPackageDto.getUnitname()))
                awardPackageDto.setUnitname(jobController.getOrgNameById(awardPackageDto.getUnitId()));
            awardPackageDtoList.add(awardPackageDto);
        }
        result.setList(awardPackageDtoList);
        return R.ok(result);
    }

    @DeleteMapping("/deleteAwardPackage")
    @ApiOperation(value = "删除薪资奖罚包信息")
    @Transactional
    public R deleteAwardPackage(@RequestParam(value = "id") String id) {
        awardPackageDao.deleteById(id);
        awardApplicantDao.delete(new QueryWrapper<AwardApplicantEntity>().eq("package_id", id));
        return R.ok();
    }


    @GetMapping("/getAwardApplicantById")
    @ApiOperation(value = "根据奖罚包id查询奖罚公司详情")
    public R getAwardApplicantById(@RequestParam(value = "id") String id) {
        List<AwardApplicantEntity> awardApplicantEntityList = awardApplicantDao.selectList(new QueryWrapper<AwardApplicantEntity>().eq("package_id", id));
        return R.ok(awardApplicantEntityList);
    }

    @PostMapping("/saveAndUpdateAwardPackage")
    @ApiOperation(value = "保存或修改奖罚包信息")
    @Transactional
    public R saveAndUpdateAwardPackage(@RequestBody @Valid AwardPackageVo awardPackageVo, HttpServletRequest request) throws Exception {
        JSONObject data = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return R.error("请先登录");
        }
        AwardPackageEntity awardPackageEntity = BeanUtilsMabach.doToDto(awardPackageVo, AwardPackageEntity.class);

        awardPackageEntity.setFileUrl(CollectionUtils.isEmpty(awardPackageVo.getFileUrlList()) ? "" : ListToString(awardPackageVo.getFileUrlList()));
        if (awardPackageVo.getId() == null) {
            String serialNum = getAwardPackageNum();
            awardPackageEntity.setSerialNum(serialNum);
            awardPackageEntity.setApplicantName(data.getString("name"));
            awardPackageEntity.setApplyTime(new Date());
            awardPackageEntity.setInsetDate(new Date());
            awardPackageEntity.setCreateCode(data.getString("usercode"));
            awardPackageEntity.setCreateName(data.getString("name"));
            awardPackageEntity.setCreateTime(new Date());
            awardPackageEntity.setJobId(data.getLong("jobId"));
            awardPackageEntity.setOrgId(data.getLong("orgId"));
            awardPackageEntity.setUnitId(data.getLong("depId"));
            awardPackageDao.insert(awardPackageEntity);
        } else {
            awardApplicantDao.delete(new QueryWrapper<AwardApplicantEntity>().eq("package_id", awardPackageEntity.getId()));
            awardPackageService.updateByIdE(awardPackageEntity);
        }
        if (!CollectionUtils.isEmpty(awardPackageVo.getAwardApplicantEntityArrayList())) {
            for (AwardApplicantEntity awardApplicantEntity : awardPackageVo.getAwardApplicantEntityArrayList()) {
                awardApplicantEntity.setAmount(awardPackageEntity.getTotalAmount());
                awardApplicantEntity.setType(awardPackageEntity.getType());
                awardApplicantEntity.setUrl(awardPackageEntity.getFileUrl());
                awardApplicantEntity.setAwardName(awardPackageEntity.getAwardName());
                awardApplicantEntity.setCreateTime(new Date());
                awardApplicantEntity.setInsetDate(new Date());
                awardApplicantEntity.setSerialNum(getSerialNum());
                awardApplicantEntity.setPackageId(awardPackageEntity.getId());
                awardApplicantEntity.setCreateCode(data.getString("usercode"));
                awardApplicantEntity.setUnitId(data.getLong("depId"));
//                awardApplicantEntity.setApplicantId(data.getLong("id"));
//                awardApplicantEntity.setApplicantName(data.getString("name"));
//                awardApplicantEntity.setDepartment(data.getString("department"));
//
//                awardApplicantEntity.setUsercode(data.getString("usercode"));
                awardApplicantService.saveE(awardApplicantEntity);
            }
        }
        return R.ok();
    }


    @GetMapping("/getAwardInfo")
    @ApiOperation(value = "根据流水号获取员工奖罚信息")
    public R getAwardInfo(@RequestParam(value = "serialNum") String serialNum) {
        List<AwardInfoEntity> awardInfoEntityList = awardInfoDao.selectList(new QueryWrapper<AwardInfoEntity>().eq("serial_num", serialNum));
        return R.ok(awardInfoEntityList);
    }


    /**
     * 保存
     */
    @PostMapping("/saveAwardInfo")
    @ApiOperation(value = "保存或修改薪资奖罚信息")
    @SysAuthorityLog(value = "保存或修改薪资奖罚信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:jffp:update')")
    public R saveAwardInfo(@RequestBody @Valid AwardInfoVo awardInfoVo, HttpServletRequest request) throws Exception {

        Long id = snowflakeIdWorker.nextId();
        JSONObject data = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return R.error("请先登录");
        }
        String serialNum = getSerialNum();
        if (awardInfoVo.getId() != null) {
            AwardApplicantEntity awardApplicantEntity = awardApplicantService.getByIdE(awardInfoVo.getId());
            if (!ObjectUtils.isEmpty(awardApplicantEntity) && !StringUtils.isEmpty(awardApplicantEntity.getSerialNum())) {
                serialNum = awardApplicantEntity.getSerialNum();
                awardInfoDao.delete(new QueryWrapper<AwardInfoEntity>().eq("serial_num", awardApplicantEntity.getSerialNum()));
            }
        }
        Long userId = data.getLong("id");
        AwardApplicantEntity awardApplicantEntity = BeanUtilsMabach.doToDto(awardInfoVo, AwardApplicantEntity.class);
        Date date = new Date();

        ArrayList<String> fileUrlList = awardInfoVo.getFileUrlList();
        awardApplicantEntity.setUrl(CollectionUtils.isEmpty(fileUrlList) ? "" : ListToString(fileUrlList));
        awardApplicantEntity.setUsercode(data.getString("usercode"));
        awardApplicantEntity.setApplicantId(data.getLong("id"));
        awardApplicantEntity.setApplicantName(data.getString("name"));
        awardApplicantEntity.setDepartment(data.getString("department"));
        if (awardInfoVo.getId() == null) {
            awardApplicantEntity.setId(id);
            awardApplicantEntity.setCreateCode(data.getString("usercode"));
            awardApplicantEntity.setUnitId(data.getLong("depId"));
            awardApplicantEntity.setApplicantId(userId);
            awardApplicantEntity.setIsDelete(0);
            awardApplicantEntity.setSerialNum(serialNum);
            awardApplicantEntity.setApprovalStatus(0);
            awardApplicantEntity.setInsetDate(date);
            awardApplicantEntity.setCreateTime(date);
            awardApplicantService.saveE(awardApplicantEntity);
        } else {
            awardApplicantService.updateByIdE(awardApplicantEntity);
        }
        if (awardInfoVo.getList() != null && awardInfoVo.getList().size() > 0) {
            for (AwardInfoEntity awardInfoEntity : awardInfoVo.getList()) {
                awardInfoEntity.setIsDelete(0);
                awardInfoEntity.setSerialNum(serialNum);
                awardInfoEntity.setCreateTime(date);
                awardInfoEntity.setDistributionId(awardApplicantEntity.getId());
                //保存附件
                EmployeeInfoEntity employeeInfoEntity = getEmployessInfoByCode(awardInfoEntity.getEmployeeCode());
                if (!CollectionUtils.isEmpty(fileUrlList)) {
                    saveFile(employeeInfoEntity.getOid(), fileUrlList, "薪资奖罚附件", 20);
                }
                awardInfoService.saveE(awardInfoEntity);
            }
        }
        return R.ok();
    }

    @GetMapping("/getComputerSubsidyPage")
    @ApiOperation("分页获取电脑补贴列表")
    public R getComputerSubsidyPage(@RequestParam(value = "code", required = false) String code,
                                    @RequestParam(value = "name", required = false) String name,
                                    @RequestParam(value = "orgName", required = false) String orgName,
                                    @RequestParam(value = "unitName", required = false) String unitName,
                                    @RequestParam(value = "jobName", required = false) String jobName,
                                    @RequestParam(value = "applyDateStart", required = false) String applyDateStart,
                                    @RequestParam(value = "applyDateEnd", required = false) String applyDateEnd,
                                    @RequestParam(value = "approveStatus", required = false) List<Integer> approveStatus,
                                    @RequestParam(value = "type", required = false) List<Integer> type,
                                    @RequestParam(value = "status", required = false) Integer status,
                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest request) throws Exception {

        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        PageResult result = computerSubsidyService.queryPage(null, null, orgIds, code, name, orgName, unitName, jobName, applyDateStart, applyDateEnd, approveStatus, type, status, pageNum, pageSize);
        return R.ok(result);
    }


    @PostMapping("/saveAndUpdateComputerSubsidy")
    @ApiOperation("保存或修改电脑补贴")
    @SysAuthorityLog("保存或修改电脑补贴")
    @Transactional
    public R saveAndUpdateComputerSubsidy(@RequestBody @Valid ComputerSubsidyVo computerSubsidyVo, HttpServletRequest request) throws Exception {
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        if (org.apache.commons.lang3.ObjectUtils.isEmpty(userInfo)) {
            return R.error("请登录");
        }
        Long oid = computerSubsidyVo.getOid();
        ComputerSubsidyEntity computerSubsidyEntity = BeanUtilsMabach.doToDto(computerSubsidyVo, ComputerSubsidyEntity.class);
        R r;
        if (!CollectionUtils.isEmpty(computerSubsidyVo.getFileUrlList())) {
            dimissionController.saveFile(oid, computerSubsidyVo.getFileUrlList(), "发票附件", 8);
        }
        computerSubsidyEntity.setFileUrl(CollectionUtils.isEmpty(computerSubsidyVo.getFileUrlList()) ? "" : dimissionController.ListToString(computerSubsidyVo.getFileUrlList()));
        computerSubsidyEntity.setApplyName(userInfo.getString("name"));
        computerSubsidyEntity.setApplyCode(userInfo.getString("usercode"));
        computerSubsidyEntity.setEquipment(2);
        computerSubsidyEntity.setStatus(0);
        if (computerSubsidyVo.getId() == null) {
            EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
            computerSubsidyEntity.setOid(oid);
            computerSubsidyEntity.setName(employeeInfoEntity.getName());
            computerSubsidyEntity.setCode(employeeInfoEntity.getCode());
            computerSubsidyEntity.setOrgId(employeeInfoEntity.getOrgId());
            computerSubsidyEntity.setUnitId(employeeInfoEntity.getUnitId());
            computerSubsidyEntity.setJobId(employeeInfoEntity.getJobId());
            computerSubsidyEntity.setJobName(jobController.getJobName(employeeInfoEntity.getJobId()));
            computerSubsidyEntity.setOrgName(jobController.getOrgNameById(employeeInfoEntity.getOrgId()));
            computerSubsidyEntity.setUnitName(jobController.getOrgNameById(employeeInfoEntity.getUnitId()));
            computerSubsidyEntity.setApplyDate(new Date());
            r = computerSubsidyService.saveE(computerSubsidyEntity);
        } else {
            r = computerSubsidyService.updateByIdE(computerSubsidyEntity);
        }
        return r;
    }

        //检查为离职人员 设置补贴为失效
        @PostMapping("/updateComputerSubsidy")
        @ApiOperation("检查为离职人员 设置补贴为失效")
        @Transactional
        public R updateComputerSubsidy() {
            List<ComputerSubsidyEntity> computerSubsidyEntityList = computerSubsidyDao.selectList(new QueryWrapper<ComputerSubsidyEntity>()
                    .eq("is_delete", 0)
                    .eq("status", 1));

            for (ComputerSubsidyEntity subsidyEntity : computerSubsidyEntityList) {
                EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(subsidyEntity.getOid());
                if ((!ObjectUtils.isEmpty(employeeInfoEntity) && "3".equals(employeeInfoEntity.getEmployeestatus()))||(new Date().compareTo(subsidyEntity.getEndDate())>0)) {
                    subsidyEntity.setStatus(2);
                    computerSubsidyService.updateByIdE(subsidyEntity);
                }

            }
         return R.ok();
        }

    @DeleteMapping("/daleteComputerSubsidy")
    @ApiOperation("删除电脑补贴")
    @SysAuthorityLog("删除电脑补贴")
    @Transactional
    public R daleteComputerSubsidy(@RequestParam(value = "id") String id) {
        computerSubsidyDao.deleteById(id);
        return R.ok();
    }

    @GetMapping("/getComputerSubsidyById")
    @ApiOperation("根据id查看电脑补贴")
    public R getComputerSubsidyById(@RequestParam(value = "id") String id) {
        ComputerSubsidyEntity computerSubsidyEntity = computerSubsidyService.getByIdE(Long.valueOf(id));
        return R.ok(computerSubsidyEntity);
    }

    @GetMapping("/getComputerSubsidyEndDate")
    @ApiOperation("查询补贴的最后结束日期")
    public R getComputerSubsidyEndDate(@RequestParam(value = "type") Integer type, @RequestParam(value = "oid") String oid, HttpServletRequest request) throws Exception {
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        if (org.apache.commons.lang3.ObjectUtils.isEmpty(userInfo)) {
            return R.error("请登录");
        }
        Date date = null;
        List<ComputerSubsidyEntity> computerSubsidyEntityList = computerSubsidyDao.selectList(new QueryWrapper<ComputerSubsidyEntity>()
                .eq("oid", oid)
                .eq("type", type)
                .eq("is_delete", 0)
                .orderByDesc("end_date"));
        if (!CollectionUtils.isEmpty(computerSubsidyEntityList)) {
            date = computerSubsidyEntityList.get(0).getEndDate();
        }
        return R.ok(date);
    }

    //附件保存
    public void saveFile(Long oid, ArrayList<String> fileList, String name, Integer type) {
        for (String s : fileList) {
            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("url", s).eq("type", type).eq("oid", oid));
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setName(name);
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setType(type);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlEntity.setUrl(s);
            imgUrlService.saveE(imgUrlEntity);
        }

    }

    public String ListToString(ArrayList<String> fileUrlList) {
        String Url = "";
        for (String s : fileUrlList) {
            Url += s + ",";
        }
        return Url.substring(0, Url.length() - 1);
    }

    public EmployeeInfoEntity getEmployessInfoByCode(String code) {
        List<EmployeeInfoEntity> employeeInfoEntitys = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("code", code).eq("is_delete", 0).orderByDesc("create_time"));
        if (!CollectionUtils.isEmpty(employeeInfoEntitys)) {
            return employeeInfoEntitys.get(0);
        }
        //        先去查询本地库，如果有则返回最新的那条
        EmployeeInfoEntity employeeInfoEntity = commonService.finEmpFromMssqlByCode(code);
        return employeeInfoEntity;
    }

    public String getSerialNum() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String datestr = format.format(date);
        String nm = new SimpleDateFormat("yyyyMMdd").format(date);
        Long max = awardApplicantDao.getAwardApplicantNum(datestr) + 1;
        String employeeOidStr = String.format("%05d", max);
        return "ZF" + nm + employeeOidStr;
    }

    public String getAwardPackageNum() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String datestr = format.format(date);
        String nm = new SimpleDateFormat("yyyyMMdd").format(date);
        Long max = awardPackageDao.getAwardPackageNum(datestr) + 1;
        String employeeOidStr = String.format("%05d", max);
        return "ZFB" + nm + employeeOidStr;
    }


//
//    /**
//     * 根据id查询工资组
//     * @return
//     */
//    public SalaryGroupDto findAllsalaryGroupByid(Long id){
//
//        Connection conn = null;
//        PreparedStatement ps = null;
//        ResultSet rs = null;
//
//        SalaryGroupDto salaryGroupDto=null;
//
//        try{
//            //加载驱动
//            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//            //获取连接
//            conn = DriverManager.getConnection("jdbc:sqlserver://192.168.70.41;databaseName = ehr", "sa", "a123456.");
//
//            String sql ="select * from tb_cnb_group where C_STATUS ='1' and c_oid_group ="+id;
//
//            //3.发送sql语句
//            ps =conn.prepareStatement(sql);
//
//
//
//            rs = ps.executeQuery();
//
//
//
//            while (rs.next()){
//                salaryGroupDto = new SalaryGroupDto();
//                salaryGroupDto.setCoidGroup(rs.getLong(1));
//                salaryGroupDto.setCname(rs.getString(2));
//                salaryGroupDto.setCpaydate(rs.getString(3));
//
//
//
//            }
//
//
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        if(rs!=null){
//            try{
//                rs.close();
//                rs=null;
//            }catch(SQLException e){
//                e.printStackTrace();
//                log.error("关闭ResultSet失败");
//            }
//        }
//        if(ps!=null){
//            try{
//                ps.close();
//                ps=null;
//            }catch(SQLException e){
//                e.printStackTrace();
//                log.error("关闭PreparedStatement失败");
//            }
//        }
//        if(conn!=null){
//            try{
//                conn.close();
//                conn=null;
//            }catch(SQLException e){
//                e.printStackTrace();
//                log.error("关闭Connection失败");
//            }
//        }
//
//
//        return salaryGroupDto;
//
//    }

    public List<Long> getOrgUnitListJob(Integer type, String name) {
        List<Long> selectOrg = null;
        //null未查询，size为0查询结果为空
//        if (0 == type) {
//            selectOrg = jobDaoMssql.findOrgByName(name);
//        } else if (1 == type) {
//            selectOrg = jobDaoMssql.findOrgByName(name);
//        } else {
//            selectOrg = jobDaoMssql.findJobIdByName(name);
//        }
        return selectOrg;
    }

    /**
     * 获取所有薪资组
     * @return
     */

//    public List<SalaryGroupDto> findAllsalaryGroupFromSsql(){
//
//        List<SalaryGroupDto> allsalaryGroupFromSsql = jobDaoMssql.findAllsalaryGroupFromSsql();
//        return allsalaryGroupFromSsql;
//    }





}
